// timed-challenge.js - 限时挑战页面的核心逻辑
// wordDataManager 现在通过全局实例使用
const app = getApp();

// 引入音频工具
const audioUtils = require('../../../utils/audioUtils');

// 初始化数据管理器
const challengeDataManager = app.getChallengeDataManager();

Page({
  data: {
    // 初始化全局数据管理器引用
    wordDataManager: null,
    // 挑战配置
    totalTime: 60, // 总时间60秒
    remainingTime: 60,
    maxHints: 3,
    hintsUsed: 0,
    coinsPerCorrect: 10,
    bonusForWin: 50,
    passingScore: 60,
    
    // 来源标志
    source: '', // 'review_magic' 或空字符串
    reviewWords: [], // 复习单词列表
    
    // 发音相关状态
    isPlaying: false,
    
    // 挑战状态
    isLoading: true,
    isChallengeCompleted: false,
    isWin: false,
    isOptionSelected: false,
    isCorrect: false,
    isScoreChanging: false,
    isLowTime: false,
    
    // 题目数据
    questions: [],
    currentQuestionIndex: 0,
    currentQuestion: {},
    selectedOption: -1,
    correctAnswerIndex: -1,
    totalQuestions: 0,
    progressPercentage: 0,
    
    // 得分数据
    currentScore: 0,
    finalScore: 0,
    coinsEarned: 0,
    finalCoins: 0,
    correctAnswers: 0,
    accuracy: 0,
    
    // 结果信息
    resultMessage: '',
    
    // 词书相关
    currentBook: null,
    books: [],
    
    // 辅助变量
    isLastQuestion: false
  },

  timerInterval: null,

  onLoad: function(options) {
    // 获取全局应用实例和数据管理器
    this.app = getApp();
    this.setData({ wordDataManager: this.app.globalData.wordDataManager });
    // 保存来源信息
    const source = options.source || '';
    this.setData({ source: source });
    
    // 获取全局魔法币管理器
    this.magicCoinManager = this.app.getMagicCoinManager();
    
    // 初始化挑战
    this.initChallenge();
  },

  // 初始化音频管理器
  initAudioManager: function() {
    if (!this.audioManager) {
      // 获取全局AudioManager实例
      this.audioManager = this.app.getAudioManager();
      this.audioManager.addStatusChangeCallback(this.onAudioStatusChange.bind(this));
    }
  },
  
  // 音频状态变化回调函数
  onAudioStatusChange: function(status) {
    this.setData({
      isPlaying: status.isPlaying
    });
  },
  
  onUnload: function() {
    // 清理计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
    
    // 移除音频状态变化回调
    if (this.audioManager) {
      this.audioManager.removeStatusChangeCallback(this.onAudioStatusChange.bind(this));
    }
  },

  // 初始化挑战
  initChallenge: function() {
    this.setData({
      isLoading: true,
      isChallengeCompleted: false,
      remainingTime: this.data.totalTime,
      hintsUsed: 0,
      currentScore: 0,
      coinsEarned: 0,
      correctAnswers: 0,
      currentQuestionIndex: 0,
      books: [],
      currentBook: null,
      isScoreChanging: false,
      isLowTime: false,
      // 确保重置所有与答案显示相关的状态
      selectedOption: -1,
      isOptionSelected: false,
      isCorrect: false,
      correctAnswerIndex: -1,
      reviewWords: []
    });
    
    // 初始化音频管理器
    this.initAudioManager();
    
    if (this.data.source === 'review_magic') {
      // 从复习页面跳转过来，使用复习单词
      this.initReviewMagicChallenge();
    } else {
      // 正常流程，获取词书列表
      this.loadBooks();
    }
  },
  
  // 初始化来自复习页面的挑战
  initReviewMagicChallenge: function() {
    try {
      const { wordDataManager } = this.data;
      // 使用全局ReviewScheduler实例
  this.reviewScheduler = this.app.getReviewScheduler();
      
      // 获取需要复习的单词
      const reviewWords = this.reviewScheduler.getWordsForReview();
      
      if (!reviewWords || reviewWords.length === 0) {
        this.setData({ isLoading: false });
        wx.showToast({
          title: '暂无需要复习的单词',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 根据复习单词的数量调整挑战时间（如果少于10个）
      const wordCount = Math.min(reviewWords.length, 10); // 最多10个单词
      let adjustedTime = 60; // 默认60秒
      
      if (wordCount < 10) {
        // 按比例调整时间
        adjustedTime = Math.floor((wordCount / 10) * 60)
      }
      
      this.setData({
        reviewWords: reviewWords,
        totalTime: adjustedTime,
        remainingTime: adjustedTime
      });
      
      // 直接生成题目
      this.generateQuestionsFromReviewWords();
    } catch (error) {
      console.error('初始化复习挑战失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({
        title: '加载复习单词失败',
        icon: 'none'
      });
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },
  
  // 加载词书列表
  loadBooks: function() {
    try {
      const { wordDataManager } = this.data;
      const books = wordDataManager.getAllBooks();
      
      if (books && books.length > 0) {
        // 按更新时间排序，最新的在前
        const sortedBooks = [...books].sort((a, b) => {
          const dateA = new Date(a.updateTime || '1970-01-01').getTime();
          const dateB = new Date(b.updateTime || '1970-01-01').getTime();
          return dateB - dateA;
        });
        
        this.setData({
          books: sortedBooks,
          currentBook: sortedBooks[0] // 默认选择第一个词书
        });
        
        // 加载词书单词并生成题目
        this.generateQuestions();
      } else {
        // 如果没有词书，显示提示
        this.setData({ isLoading: false });
        wx.showToast({
          title: '请先选择词书',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('加载词书失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({
        title: '加载词书失败',
        icon: 'none'
      });
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 从复习单词生成题目
  generateQuestionsFromReviewWords: function() {
    try {
      const reviewWords = this.data.reviewWords;
      
      if (!reviewWords || reviewWords.length === 0) {
        this.setData({ isLoading: false });
        wx.showToast({
          title: '暂无需要复习的单词',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 限制最多10个单词
      const selectedWords = this.selectRandomWords(reviewWords, Math.min(10, reviewWords.length));
      
      // 生成题目
      const questions = this.createQuestionsFromWords(selectedWords);
      
      this.setData({
        questions: questions,
        totalQuestions: questions.length,
        currentQuestion: questions.length > 0 ? questions[0] : {},
        correctAnswerIndex: questions.length > 0 ? questions[0].correctAnswerIndex : -1,
        isLastQuestion: questions.length > 0 ? questions.length === 1 : false,
        progressPercentage: questions.length > 0 ? Math.round((1 / questions.length) * 100) : 0,
        isLoading: false
      });
      
      // 开始倒计时
      this.startTimer();
    } catch (error) {
      console.error('从复习单词生成题目失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({
        title: '生成挑战题目失败',
        icon: 'none'
      });
    }
  },
  
  // 生成挑战题目
  generateQuestions: function() {
    try {
      const { wordDataManager } = this.data;
      // 获取当前词书的单词
      const currentBook = this.data.currentBook;
      if (!currentBook || !currentBook.wordIds || currentBook.wordIds.length === 0) {
        this.setData({ isLoading: false });
        wx.showToast({
          title: '当前词书没有单词',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 获取词书中的单词
      let words = this.data.wordDataManager.getWordsByBookId(currentBook.id);
      
      if (!words || words.length === 0) {
        this.setData({ isLoading: false });
        wx.showToast({
          title: '当前词书没有单词',
          icon: 'none'
        });
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
      
      // 根据学习情况选择单词
      const selectedWords = this.selectWordsByLearningStatus(words);
      
      // 生成题目
      const questions = this.createQuestionsFromWords(selectedWords);
      
      this.setData({
        questions: questions,
        totalQuestions: questions.length,
        currentQuestion: questions.length > 0 ? questions[0] : {},
        correctAnswerIndex: questions.length > 0 ? questions[0].correctAnswerIndex : -1,
        isLastQuestion: questions.length > 0 ? questions.length === 1 : false,
        progressPercentage: questions.length > 0 ? Math.round((1 / questions.length) * 100) : 0,
        isLoading: false
      });
      
      // 开始倒计时
      this.startTimer();
    } catch (error) {
      console.error('生成题目失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({
        title: '生成挑战题目失败',
        icon: 'none'
      });
    }
  },
  
  // 根据学习情况选择单词
  selectWordsByLearningStatus: function(words) {
    const { wordDataManager } = this.data;
    // 按学习情况分组
    const unlearnedWords = [];
    const learnedButNotMasteredWords = [];
    const masteredWords = [];
    
    words.forEach(word => {
      const learnCount = this.data.wordDataManager.getWordLearnCount(word.id);
      const isMemorized = this.data.wordDataManager.getWordMemorizedStatus(word.id);
      
      if (learnCount === 0) {
        // 未学习的单词
        unlearnedWords.push(word);
      } else if (!isMemorized || learnCount < 3) {
        // 已学习但未掌握的单词
        learnedButNotMasteredWords.push(word);
      } else {
        // 已掌握的单词
        masteredWords.push(word);
      }
    });
    
    // 确定选择策略
    const totalNeeded = Math.min(10, words.length); // 最多10个单词
    const selectedWords = [];
    
    // 优先选择未学习的单词
    if (unlearnedWords.length > 0) {
      const count = Math.min(Math.floor(totalNeeded * 0.5), unlearnedWords.length);
      selectedWords.push(...this.selectRandomWords(unlearnedWords, count));
    }
    
    // 其次选择已学习但未掌握的单词
    if (learnedButNotMasteredWords.length > 0 && selectedWords.length < totalNeeded) {
      const remainingSlots = totalNeeded - selectedWords.length;
      const count = Math.min(Math.floor(remainingSlots * 0.8), learnedButNotMasteredWords.length);
      selectedWords.push(...this.selectRandomWords(learnedButNotMasteredWords, count));
    }
    
    // 最后选择已掌握的单词
    if (masteredWords.length > 0 && selectedWords.length < totalNeeded) {
      const remainingSlots = totalNeeded - selectedWords.length;
      selectedWords.push(...this.selectRandomWords(masteredWords, remainingSlots));
    }
    
    // 如果还不够，从所有单词中补充
    if (selectedWords.length < totalNeeded) {
      const allWordsExceptSelected = words.filter(word => 
        !selectedWords.some(selected => selected.id === word.id)
      );
      const remainingSlots = totalNeeded - selectedWords.length;
      selectedWords.push(...this.selectRandomWords(allWordsExceptSelected, remainingSlots));
    }
    
    // 随机排序
    return selectedWords.sort(() => Math.random() - 0.5);
  },
  
  // 从单词数组中随机选择指定数量的单词
  selectRandomWords: function(wordArray, count) {
    const shuffled = [...wordArray].sort(() => Math.random() - 0.5);
    return shuffled.slice(0, count);
  },
  
  // 从单词创建题目
  createQuestionsFromWords: function(words) {
    const { wordDataManager } = this.data;
    const questions = [];
    const allWords = this.data.wordDataManager.getAllWords();
    const allWordArray = Object.values(allWords);
    
    words.forEach(word => {
      // 为每个单词创建题目
      const question = this.createQuestionForWord(word, allWordArray);
      if (question) {
        questions.push(question);
      }
    });
    
    return questions;
  },
  
  // 为单个单词创建题目
  createQuestionForWord: function(word, allWordArray) {
    try {
      // 正确答案
      const correctAnswer = word.chinese || '未知';
      
      // 收集其他可能的选项（干扰项）
      const distractors = [];
      const MAX_DISTRACTORS = 3; // 最多3个干扰项
      
      // 随机选择其他单词的中文释义作为干扰项
      const shuffledWords = [...allWordArray].sort(() => Math.random() - 0.5);
      
      for (let i = 0; i < shuffledWords.length && distractors.length < MAX_DISTRACTORS; i++) {
        const distractorWord = shuffledWords[i];
        const distractor = distractorWord.chinese || '未知';
        
        // 确保干扰项不是正确答案且不重复
        if (distractor !== correctAnswer && !distractors.includes(distractor)) {
          distractors.push(distractor);
        }
      }
      
      // 如果干扰项不足，使用通用干扰项
      if (distractors.length < MAX_DISTRACTORS) {
        const commonDistractors = ['未知', '不确定', '不记得', '不认识'];
        for (let i = 0; i < commonDistractors.length && distractors.length < MAX_DISTRACTORS; i++) {
          const distractor = commonDistractors[i];
          if (distractor !== correctAnswer && !distractors.includes(distractor)) {
            distractors.push(distractor);
          }
        }
      }
      
      // 组合所有选项
      const allOptions = [correctAnswer, ...distractors];
      
      // 打乱选项顺序
      const shuffledOptions = [...allOptions].sort(() => Math.random() - 0.5);
      
      // 找到正确答案在打乱后的索引
      const correctIndex = shuffledOptions.indexOf(correctAnswer);
      
      // 返回题目对象
      // 处理pronunciation对象，提取具体的音标字符串
      let phoneticText = '';
      if (word.pronunciation) {
        // 优先使用美式音标，如果没有则使用英式音标
        if (word.pronunciation.us) {
          phoneticText = word.pronunciation.us;
        } else if (word.pronunciation.uk) {
          phoneticText = word.pronunciation.uk;
        }
      }
      
      return {
        id: word.id,
        word: word.english || '未知',
        phonetic: phoneticText,
        pronunciation: word.pronunciation || {}, // 保留完整的pronunciation对象
        definition: correctAnswer,
        options: shuffledOptions,
        correctAnswerIndex: correctIndex
      };
    } catch (error) {
      console.error('创建题目失败:', error);
      return null;
    }
  },

  // 开始倒计时
  startTimer: function() {
    this.timerInterval = setInterval(() => {
      let remaining = this.data.remainingTime - 1;
      
      if (remaining <= 0) {
        // 时间到，结束挑战
        clearInterval(this.timerInterval);
        this.completeChallenge();
      } else {
        // 判断是否进入低时间警告状态
        const isLowTime = remaining <= 15;
        
        this.setData({
          remainingTime: remaining,
          isLowTime: isLowTime
        });
        
        // 在时间不多时可以添加震动提示
        if (remaining <= 10 && remaining % 2 === 0) {
          wx.vibrateShort();
        }
      }
    }, 1000);
  },

  // 选择答案选项
  selectOption: function(e) {
    const { wordDataManager } = this.data;
    if (this.data.isOptionSelected) return;
    
    const selectedIndex = e.currentTarget.dataset.index;
    const isCorrect = selectedIndex === this.data.correctAnswerIndex;
    const currentQuestion = this.data.currentQuestion;
    
    // 计算得分
    let scoreToAdd = 0;
    let coinsToAdd = 0;
    let correctCount = this.data.correctAnswers;
    
    if (isCorrect) {
      // 答对了，根据剩余时间计算得分
      scoreToAdd = Math.floor(100 * (this.data.remainingTime / this.data.totalTime));
      coinsToAdd = this.data.coinsPerCorrect;
      correctCount++;
      
      // 更新单词的学习状态
      if (currentQuestion.id) {
        this.data.wordDataManager.incrementWordLearnCount(currentQuestion.id);
        
        // 如果学习次数达到一定阈值，可以自动标记为已掌握
        const learnCount = this.data.wordDataManager.getWordLearnCount(currentQuestion.id);
        if (learnCount >= 3 && !this.data.wordDataManager.getWordMemorizedStatus(currentQuestion.id)) {
          this.data.wordDataManager.setWordMemorizedStatus(currentQuestion.id, true);
        }
      }
    } else {
      // 答错了，如果单词已标记为已掌握，可以取消标记
      if (currentQuestion.id) {
        const isMemorized = this.data.wordDataManager.getWordMemorizedStatus(currentQuestion.id);
        if (isMemorized) {
          this.data.wordDataManager.setWordMemorizedStatus(currentQuestion.id, false);
        }
      }
    }
    
    // 播放音效
    audioUtils.playSound(isCorrect ? 'right' : 'wrong');

    // 如果得分增加了，触发分数变化动画
    if (scoreToAdd > 0) {
    this.setData({
      selectedOption: selectedIndex,
      isOptionSelected: true,
      isCorrect: isCorrect,
      currentScore: this.data.currentScore + scoreToAdd,
      coinsEarned: this.data.coinsEarned + coinsToAdd,
      correctAnswers: correctCount,
      isScoreChanging: true
    });
    
    // 动画结束后重置状态
    setTimeout(() => {
      this.setData({ isScoreChanging: false });
      
      // 检查是否是最后一题，如果是则自动完成挑战
      if (this.data.isLastQuestion) {
        this.completeChallenge();
      }
    }, 500);
  } else {
    this.setData({
      selectedOption: selectedIndex,
      isOptionSelected: true,
      isCorrect: isCorrect,
      currentScore: this.data.currentScore + scoreToAdd,
      coinsEarned: this.data.coinsEarned + coinsToAdd,
      correctAnswers: correctCount
    });
    
    // 检查是否是最后一题，如果是则自动完成挑战
    if (this.data.isLastQuestion) {
      setTimeout(() => {
        this.completeChallenge();
      }, 500);
    }
  }
  },

  // 进入下一题
  goToNextQuestion: function() {
    if (this.data.currentQuestionIndex >= this.data.totalQuestions - 1) {
      // 已经是最后一题
      this.completeChallenge();
      return;
    }
    
    const nextIndex = this.data.currentQuestionIndex + 1;
    const isLastQuestion = nextIndex >= this.data.totalQuestions - 1;
    
    const progressPercentage = Math.round(((nextIndex + 1) / this.data.totalQuestions) * 100);
    
    this.setData({
      currentQuestionIndex: nextIndex,
      currentQuestion: this.data.questions[nextIndex],
      correctAnswerIndex: this.data.questions[nextIndex].correctAnswerIndex,
      selectedOption: -1,
      isOptionSelected: false,
      isCorrect: false,
      isLastQuestion: isLastQuestion,
      progressPercentage: progressPercentage
    });
  },

  // 显示提示
  showHint: function() {
    if (this.data.hintsUsed >= this.data.maxHints || this.data.isOptionSelected) {
      return;
    }
    
    // 为正确选项添加动画特效
    this.setData({
      hintsUsed: this.data.hintsUsed + 1,
      hintAnimation: this.data.correctAnswerIndex
    });
    
    // 3秒后移除动画效果
    setTimeout(() => {
      this.setData({
        hintAnimation: -1
      });
    }, 3000);
  },

  // 播放发音
  playPronunciation: function() {
    const { isPlaying, currentQuestion } = this.data;
    
    // 如果正在播放，停止播放
    if (isPlaying) {
      if (this.audioManager) {
        this.audioManager.stopPronunciation();
      }
      return;
    }
    
    if (!currentQuestion || !currentQuestion.word) {
      wx.showToast({
        title: '当前没有单词可播放',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    
    // 初始化音频管理器
    this.initAudioManager();
    
    // 默认使用美式发音和正常速度
    const pronunciationType = 'american';
    const playbackSpeed = 1.0;
    
    // 现在直接传入单词对象，让audioManager内部处理音频URL获取和错误处理
    this.audioManager.playPronunciation(currentQuestion, playbackSpeed, pronunciationType)
      .then(() => {
        console.log('播放成功');
      })
      .catch(error => {
        console.error('播放失败:', error);
        wx.showToast({
          title: '播放失败',
          icon: 'none',
          duration: 2000
        });
      });
  },

  // 完成挑战
  completeChallenge: function() {
    // 清理计时器
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
    
    // 计算最终结果
    const accuracy = Math.round((this.data.correctAnswers / this.data.totalQuestions) * 100);
    const isWin = this.data.currentScore >= this.data.passingScore;
    let finalCoins = this.data.coinsEarned;
    let resultMessage = '';
    
    // 胜利奖励
    if (isWin) {
      finalCoins += this.data.bonusForWin;
      
      if (accuracy >= 90) {
        resultMessage = '太棒了！你是单词小达人！';
      } else if (accuracy >= 70) {
        resultMessage = '做得很好！继续保持！';
      } else {
        resultMessage = '恭喜通过！再接再厉！';
      }
    } else {
      resultMessage = '别灰心，再试一次吧！';
    }
    
    this.setData({
      isChallengeCompleted: true,
      isWin: isWin,
      finalScore: this.data.currentScore,
      finalCoins: finalCoins,
      accuracy: accuracy,
      resultMessage: resultMessage
    });
    
    // 保存挑战结果到本地存储
    this.saveChallengeResult();
  },

  // 保存挑战结果
  saveChallengeResult: function() {
    try {
      // 构建挑战记录
      const challengeRecord = {
        type: '限时挑战',
        date: new Date().toISOString(),
        isWin: this.data.isWin,
        score: this.data.finalScore,
        duration: this.data.totalTime - this.data.remainingTime,
        correctAnswers: this.data.correctAnswers,
        totalQuestions: this.data.totalQuestions
      };
      
      // 保存挑战记录
      challengeDataManager.addChallengeRecord(challengeRecord);
      
      // 更新魔法币
      if (this.data.finalCoins > 0) {
        this.magicCoinManager.addMagicCoins(this.data.finalCoins);
      }
      
      console.log('限时挑战结果保存成功');
    } catch (e) {
      console.error('保存挑战结果失败:', e);
    }
  },

  // 再玩一次
  playAgain: function() {
    this.initChallenge();
  },

  // 返回挑战主页
  backToChallenge: function() {
    wx.navigateBack();
  },

  // 分享挑战
  onShareAppMessage: function() {
    return {
      title: `我在限时挑战中获得了${this.data.finalScore}分！快来挑战吧！`,
      path: '/pages/challenge/timed-challenge',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在限时挑战中获得了${this.data.finalScore}分！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});